package com.bizmda.bizsip.source.rest.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.source.api.SourceBeanInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 史正烨
 */
@Slf4j
@RestController
public class RestSourceController {
    @Autowired
    private SourceBeanInterface restSourceService;

    @PostMapping(value = "/rest", consumes = "application/json", produces = "application/json")
    public Object doService(HttpServletRequest request,@RequestBody JSONObject inMessage) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String,String> headerMap = new HashMap<>(16);
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            // 排除Cookie字段
            if ("Cookie".equalsIgnoreCase(key)) {
                continue;
            }
            String value = request.getHeader(key);
            headerMap.put(key, value);
        }
        RestSourceDTO restSourceDTO = RestSourceDTO.builder()
                .headerMap(headerMap).jsonObjectData(inMessage).build();
        Object outMessage = null;
        try {
            outMessage = this.restSourceService.process(restSourceDTO);
            return outMessage;
        } catch (BizException e) {
            return JSONUtil.createObj()
                    .set("code", e.getCode())
                    .set("message", e.getMessage())
                    .set("extMessage", e.getExtMessage());
        }
    }
}